package code.class3.easy;

import common.ArrayUtils;

import java.util.ArrayList;
import java.util.List;

public class TestDemo {
    public static void main(String[] args) {
        String str = "loveleetcode";
        char c = 'e';
        int[] ints = shortestToChar(str, c);
        ArrayUtils.printArr(ints);
    }

    public static int[] shortestToChar(String s, char c) {
        int n = s.length();
        int[] answer = new int[n];
        int prev = -1; // prev 为 -1 表示当前还没有遇到字符 c
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == c) {
                prev = i;
                answer[i] = 0; // 找到字符 c，距离为 0
            } else if (prev != -1) {
                answer[i] = i - prev; // 计算当前字符与上一个 'c' 之间的距离
            } else {
                answer[i] =Integer.MAX_VALUE;
            }
        }
        // 第二次遍历：从右到左计算距离，并取最小值
        prev = -1; // 重置 prev
        for (int i = n - 1; i >= 0; i--) {
            if (s.charAt(i) == c) {
                prev = i;
                answer[i] = 0; // 找到字符 c，距离为 0
            } else if (prev != -1) {
                answer[i] = Math.min(answer[i], prev - i); // 取最小距离
            }
        }
        return answer;
    }
}
